//
//  CZPlaceholderTextView.swift
//  GZWeibo009
//
//  Created by gzxzmac on 16/3/31.
//  Copyright © 2016年 gzxzmac. All rights reserved.
//

import UIKit

class CZPlaceholderTextView: UITextView {
    
    // 覆盖父类的属性: 1.override 2.实现didSet
    // 子类是对父类的扩展,属性赋值是先给父类赋值,在给子类
    override var text: String? {
        didSet {
            // textView有文本就隐藏
            placeholderLabel.hidden = self.hasText()
        }
    }
    
    override var font: UIFont? {
        didSet {
            placeholderLabel.font = font
        }
    }
    
    /// 设置占位文本
    var placeholder: String? {
        didSet {
            placeholderLabel.text = placeholder
        }
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)
        
        prepareUI()
        
        // 代理: 1对1, 要注意覆盖,这里先设置,然后被控制器覆盖了,所以只有控制器能监听到文字的改变
        // 通知是一对多的.里面使用通知,外面覆盖不了.外面用什么对我们都没有干扰
        // object: 通知的发送者, nil: 只要发送TextDidChange通知就能监听到. object:指定对象,只有这个对象发送的才能监听到
        // 别人发送的通知不关心,只关心自己的文字改变
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "textDidChange", name: UITextViewTextDidChangeNotification, object: self)
//        self.delegate = self
    }
    
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    func textDidChange() {
        placeholderLabel.hidden = hasText()
    }

    private func prepareUI() {
        // 添加子控件
        addSubview(placeholderLabel)
        
        // 添加约束
        placeholderLabel.translatesAutoresizingMaskIntoConstraints = false
        
        addConstraint(NSLayoutConstraint(item: placeholderLabel, attribute: NSLayoutAttribute.Leading, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Leading, multiplier: 1, constant: 5))
        
        addConstraint(NSLayoutConstraint(item: placeholderLabel, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: 8))
    }

    // MARK: - 懒加载
    /// 占位的label
    private lazy var placeholderLabel: UILabel = {
        // 添加label
        let label = UILabel()
        label.font = UIFont.systemFontOfSize(18)
        label.textColor = UIColor.lightGrayColor()
        label.sizeToFit()
        
        return label
    }()
}

// MARK: - 扩展
extension CZPlaceholderTextView: UITextViewDelegate {
    // 当文字发生改变时调用
    func textViewDidChange(textView: UITextView) {
        // textView有文本就隐藏
        placeholderLabel.hidden = textView.hasText()
    }
}
